package com.twetec.cms.adapter.pc.backend.controller.website;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.twetec.cms.adapter.pc.backend.annotion.SitePermission;
import com.twetec.cms.adapter.pc.backend.response.R;
import com.twetec.cms.adapter.pc.backend.response.ResultCodeMsgEnum;
import com.twetec.cms.adapter.pc.backend.util.beetl.html.BeetlStaticHtml;
import com.twetec.cms.common.constant.*;
import com.twetec.cms.common.util.validate.ValidateUtil;
import com.twetec.cms.model.po.system.CmsMenuPO;
import com.twetec.cms.model.po.system.CmsRoleMenuPO;
import com.twetec.cms.model.po.system.CmsUserRolePO;
import com.twetec.cms.model.po.system.StaticLogPO;
import com.twetec.cms.model.po.user.UserPO;
import com.twetec.cms.model.po.website.*;
import com.twetec.cms.model.vo.website.*;
import com.twetec.cms.service.file.FastdfsFileService;
import com.twetec.cms.service.system.CmsMenuService;
import com.twetec.cms.service.system.CmsRoleMenuService;
import com.twetec.cms.service.system.CmsUserRoleService;
import com.twetec.cms.service.system.StaticLogService;
import com.twetec.cms.service.ucenter.UserService;
import com.twetec.cms.service.website.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Api(tags = "栏目操作模块")
@RestController
@RequestMapping("/website/column")
public class ColumnController {

    @Value("${twetec.resource.preview-root-path}")
    private String previewPath;

    @Value("${twetec.resource.preview-root-url}")
    private String previewUrl;

    @Autowired
    private StaticHtmlController staticHtmlController;

    @Autowired
    private ColumnService columnService;

    @Autowired
    private SiteColumnService siteColumnService;

    @Autowired
    private SiteService siteService;

    @Autowired
    private UserService userService;

    @Autowired
    private ColumnArticleModelService columnArticleModelService;

    @Autowired
    private ArticleModelService articleModelService;

    @Autowired
    private WebsiteTemplateService templateService;

    @Autowired
    private FastdfsFileService fastdfsFileService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private BeetlStaticHtml beetlStaticHtml;

    @Autowired
    private CmsMenuService cmsMenuService;

    @Autowired
    private CmsRoleMenuService cmsRoleMenuService;

    @Autowired
    private CmsUserRoleService cmsUserRoleService;

    @Autowired
    private ArticleExtendService articleExtendService;

    @Autowired
    private ArticleAttachmentService articleAttachmentService;

    @Autowired
    private ArticleRelevantService articleRelevantService;

    @Autowired
    private ColumnReferenceRelationshipService columnReferenceRelationshipService;

    @Autowired
    private ColumnReferenceArticleService columnReferenceArticleService;


    @Autowired
    private StaticLogService staticLogService;

    private static final String COLUMN_PAGE = "column:get-child-column-by-parent-column-id";
    private static final String CREATE = "column:create";
    private static final String UPDATE = "column:update-column-by-id";
    private static final String DETAIL = "column:get-column-by-id";
    private static final String REMOVE_BY_ID = "column:remove-by-id";
    private static final String REMOVE_BY_IDS = "column:remove-by-ids";
    private static final String RECOVERY_BY_ID = "column:recovery-by-id";
    private static final String RECOVERY_BY_IDS = "column:recovery-by-ids";
    private static final String GET_COLUMN_ARTICLE_MODEL_BY_COLUMN_ID = "column:get-column-article-model-by-column-id";
    private static final String SAVE_OR_UPDATE_COLUMN_ARTICLE_MODEL_BY_COLUMN_ID = "column:save-or-update-column-article-model-by-column-id";
    private static final String GET_SEO_BY_ID = "column:get-seo-by-id";
    private static final String UPDATE_BY_ID = "column:update-by-id";
    private static final String UPDATE_VERIFY_STATUS_BY_COLUMN_ID = "column:update-verify-status-by-column-id";
    private static final String GET_RECOVERY_CHILD_COLUMN_BY_PARENT_COLUMN_ID = "column:get-recovery-child-column-by-parent-column-id";

    @SitePermission({CREATE})
    @Transactional
    @ApiOperation(value = "创建新栏目", notes = "创建新栏目")
    @PostMapping("/create")
    public R create(@ApiParam(value = "站点id", required = true, example = "1435204946847760385") @RequestParam(required = false) Long siteId,
                    @ApiParam(value = "父栏目id（如果是顶级栏目就传Long类型的0）", required = true, example = "1435204946847760385") @RequestParam(required = false) Long parentId,
                    @ApiParam(value = "栏目名称", required = true, example = "关于我们") @RequestParam(required = false) String name,
                    @ApiParam(value = "栏目编码(小写英文字母和下划线组成)", required = true, example = "ghsc") @RequestParam(required = false) String encoded,
                    @ApiParam(value = "栏目类型(接口获取)", required = true, example = "PIN_DAO_FENG_MIAN") @RequestParam(required = false) String type,
                    @ApiParam(value = "跳转地址", required = false, example = "http://xxx.com/xxx") @RequestParam(required = false) String jumpUrl,
                    @ApiParam(value = "每页条目数", required = false, example = "8") @RequestParam(required = false) Integer pageLimit,
                    @ApiParam(value = "栏目模板pc端(被栏目使用)", required = false, example = "1435204946847760385") @RequestParam(required = false) Long pcTemplateId,
                    @ApiParam(value = "栏目模板h5端(被栏目使用)", required = false, example = "1435204946847760385") @RequestParam(required = false) Long h5TemplateId,
                    @ApiParam(value = "序号", required = false, example = "0") @RequestParam(required = false) Integer sort,
                    @ApiParam(value = "是否在导航中显示 (0否，1是)", required = true, example = "1") @RequestParam(required = false) Integer nav,
                    @ApiParam(value = "PC端模板路径(被栏目使用)", required = false, example = "1") @RequestParam(required = false) String pcTemplateFilePath,
                    @ApiParam(value = "H5端模板路径(被栏目使用)", required = false, example = "1") @RequestParam(required = false) String h5TemplateFilePath,
                    @ApiParam(value = "栏目logo(地址)", required = false, example = "E://11.jpg") @RequestParam(required = false) String logo,
                    @RequestAttribute("userId") Long userId) {

        // 父栏目id
        if (parentId == null || !ValidateUtil.Number(parentId) || parentId < 0)
            return R.failureRequestParam().msg("父级栏目id输入有误");
        // 栏目名称
        if (StringUtils.isEmpty(name)) return R.failureRequestParam().msg("栏目名称不能为空");
        // 栏目编码
        if (StringUtils.isEmpty(encoded)) return R.failureRequestParam().msg("栏目编码不能为空");
        Boolean resultEncoded = columnService.checkColumnEncoded(siteId, parentId, null, encoded);
        if (!resultEncoded) return R.failure().msg("栏目编码重复");
        // 栏目类型
        if (StringUtils.isEmpty(type)) return R.failureRequestParam().msg("栏目类型不能为空");

        // 是否在导航中显示 (0默认，1导航)
        if (nav == null) return R.failureRequestParam().msg("请选择该栏目是否在导航栏中显示");
        if (pcTemplateId == null) pcTemplateId = 0L;
        if (h5TemplateId == null) h5TemplateId = 0L;

//        Long userId = 1371387567439171585L;
        // 执行增加
        ColumnPO columnPO = new ColumnPO();
        columnPO.setParentId(parentId);
        columnPO.setName(name);
        columnPO.setEncoded(encoded);
        columnPO.setType(type);
        columnPO.setPcTemplateId(pcTemplateId);
        columnPO.setH5TemplateId(h5TemplateId);
        columnPO.setNav(nav);
        if (sort != null && ValidateUtil.Number(sort)) columnPO.setSort(sort);
        columnPO.setCreatorId(userId);
        columnPO.setModifierId(userId);
        columnPO.setPcTemplatePath(pcTemplateFilePath);
        columnPO.setH5TemplatePath(h5TemplateFilePath);
        columnPO.setLogo(logo);
        columnPO.setJumpUrl(jumpUrl);
        columnPO.setPageLimit(pageLimit);

        String columnXpath = "";
        // 维护xpath和encodedXpath
        String encodedXpath = "/" + encoded;
        if (parentId.equals(0L)) {
            columnPO.setXpath("0");
            columnPO.setEncodedXpath(encodedXpath);
        } else {
            ColumnPO columnPOById = columnService.getById(parentId);
            if (columnPOById != null) {
                columnXpath = columnPOById.getXpath() + "-" + parentId;
                columnPO.setXpath(columnXpath);
                columnPO.setEncodedXpath(columnPOById.getEncodedXpath() + encodedXpath);
            }
        }
        // 添加栏目
        boolean result = columnService.save(columnPO);

        if (!result) return R.failure().msg("栏目添加失败");


        // 添加顶级栏目与站点的关系
        if (parentId.equals(0L)) {
            SiteColumnPO siteColumnPO = new SiteColumnPO();
            siteColumnPO.setSiteId(siteId);
            siteColumnPO.setColumnId(columnPO.getId());
            boolean save = siteColumnService.save(siteColumnPO);
            if (!save) {
                return R.failure().msg("栏目添加失败");
            }
        }

        // TODO:: 添加栏目的菜单权限
        ArrayList<CmsMenuPO> cmsMenuPOS = cmsMenuService.addColumnPermission(columnPO.getId(), name, siteId, parentId, columnXpath, userId);

        // 将栏目的菜单权限添加给用户角色
        if (!cmsMenuPOS.isEmpty()) {
            // 获取用户对应的角色ID
            QueryWrapper<CmsUserRolePO> cmsUserRolePOQueryWrapper = new QueryWrapper<>();
            cmsUserRolePOQueryWrapper.lambda().eq(CmsUserRolePO::getUserId, userId);
            List<CmsUserRolePO> cmsUserRolePOS = cmsUserRoleService.list(cmsUserRolePOQueryWrapper);
            if (null == cmsUserRolePOS) {
                return R.failure().msg("权限添加失败");
            }

            ArrayList<Long> menuIdList = new ArrayList<>();
            for (CmsMenuPO cmsMenuPO : cmsMenuPOS) {
                menuIdList.add(cmsMenuPO.getId());
            }

            StringBuffer roleIds = new StringBuffer();
            for (CmsUserRolePO userRolePO : cmsUserRolePOS) {
                roleIds.append(userRolePO.getRoleId());
                roleIds.append(",");
            }
            String roleIdStr = roleIds.substring(0, roleIds.lastIndexOf(","));
            boolean menuRelative = cmsRoleMenuService.addRoleMenuRelative(roleIdStr, menuIdList);
            if (!menuRelative) {
                return R.failure().msg("权限添加失败");
            }
        }

        boolean deleteUserPermission = cmsRoleMenuService.deleteUserPermission();

        return R.success().msg("栏目添加成功");
    }


    @ApiOperation(value = "获取栏目类型列表", notes = "获取栏目类型列表")
    @GetMapping("/type-list")
    public R<ColumnTypeVO> typeList() {
        // 获取枚举类的集合
        List<HashMap<String, String>> columnEnumList = ColumnEnum.getColumnEnumList();

        // 存放要返回的TypeVO集合
        ArrayList<TypeVO> typeVOList = new ArrayList<>();

        for (int i = 0; i < columnEnumList.size(); i++) {
            HashMap<String, String> hashMap = columnEnumList.get(i);
            TypeVO typeVO = new TypeVO();
            // 遍历存到
            hashMap.forEach((key, value) -> {
                typeVO.setKey(key);
                typeVO.setValue(value);
                typeVOList.add(typeVO);
            });

        }
        // 封装对象
        ColumnTypeVO columnTypeVO = new ColumnTypeVO();
        columnTypeVO.setList(typeVOList);

        return R.success().data(columnTypeVO);
    }


    @ApiOperation(value = "栏目编码数据校验", notes = "栏目编码数据校验")
    @GetMapping("/encoded-data-check")
    public R encodedDataCheck(@ApiParam(value = "站点id", required = true, example = "1435204946847760385") @RequestParam(required = false) Long siteId,
                              @ApiParam(value = "父栏目id（如果是顶级栏目就传Long类型的0）", required = true, example = "123456789111") @RequestParam(required = false) Long parentId,
                              @ApiParam(value = "当前栏目id（若是新建栏目就不传，若是更新就传）", required = false, example = "123456789111") @RequestParam(required = false) Long columnId,
                              @ApiParam(value = "栏目编码", required = true, example = "pin_dao_feng_mian") @RequestParam(required = false) String encoded) {

        // 栏目编码数据校验
//        if (siteId == null || !ValidateUtil.Number(siteId) || siteId < 0)
//            return R.failureRequestParam().msg("站点id为空或格式不正确");
//        if (StringUtils.isEmpty(encoded)) return R.failureRequestParam().msg("栏目编码为空");
//        if (parentId == null || !ValidateUtil.Number(parentId) || parentId < 0)
//            return R.failureRequestParam().msg("父栏目id为空或格式不正确");
//        Boolean result = columnService.checkColumnEncoded(siteId, parentId, columnId, encoded);
//        if (result) return R.success();
        return R.success();
    }

    @SitePermission({GET_SEO_BY_ID})
    @ApiOperation(value = "根据栏目id获取seo", notes = "根据栏目id获取seo")
    @GetMapping("/get-seo-by-id")
    public R<SeoVO> getSeoById(@ApiParam(value = "栏目id", required = true, example = "1440511661143220226") @RequestParam(required = false) Long columnId) {

        // 参数校验
        if (null == columnId || !ValidateUtil.Number(columnId) || columnId <= 0)
            return R.failureRequestParam().msg("栏目id为空或格式不正确");

        // 根据栏目id获取栏目信息
        ColumnPO columnPO = columnService.getById(columnId);
        if (columnPO == null) return R.resultCodeMsg(ResultCodeMsgEnum.DATA_NOT_EXIST);

        // 封装到VO返回
        SeoVO seoVO = new SeoVO();
        BeanUtils.copyProperties(columnPO, seoVO);
        return R.success().data(seoVO);
    }

    @SitePermission({UPDATE_BY_ID})
    @ApiOperation(value = "修改seo", notes = "修改seo")
    @PutMapping("/update-by-id")
    public R updateById(@ApiParam(value = "栏目id", required = true, example = "1440511661143220226") @RequestParam(required = false) Long columnId,
                        @ApiParam(value = "seo标题", required = true, example = "搜索优化") @RequestParam(required = false) String seoTitle,
                        @ApiParam(value = "seo关键字（字符串类型）", required = true, example = "工会,厦门") @RequestParam(required = false) String seoKeywords,
                        @ApiParam(value = "seo描述", required = true, example = "厦门市总工会门户网站") @RequestParam(required = false) String seoDesc,
                        @RequestAttribute("userId") Long userId) {

        // 参数校验
        if (null == columnId || !ValidateUtil.Number(columnId) || columnId <= 0)
            return R.failureRequestParam().msg("栏目id为空或格式不正确");
        if (StringUtils.isEmpty(seoTitle)) return R.failureRequestParam().msg("栏目标题为空或空字符串");
        if (StringUtils.isEmpty(seoKeywords)) return R.failureRequestParam().msg("栏目关键字为空或空字符串");
        if (StringUtils.isEmpty(seoDesc)) return R.failureRequestParam().msg("seo描述为空或空字符串");

        // TODO:: 打包时userId要注释
//        Long userId = 1371387567439171585L;

        // 添加要修改的属性值
        ColumnPO columnPO = new ColumnPO();
        columnPO.setId(columnId);
        columnPO.setSeoTitle(seoTitle);
        columnPO.setSeoKeywords(seoKeywords);
        columnPO.setSeoDesc(seoDesc);
        columnPO.setModifierId(userId);

        // 调用方法进行修改
        boolean result = columnService.updateById(columnPO);
        if (result) return R.success();
        return R.failure();
    }

    @SitePermission({REMOVE_BY_ID})
    @Transactional
    @ApiOperation(value = "根据id回收栏目", notes = "根据id回收栏目")
    @PutMapping("/remove-by-id")
    public R removeById(
            @ApiParam(value = "id", required = true, example = "12312313123") @RequestParam(required = false) Long id,
            @RequestAttribute("userId") Long userId) {

        // 校验id
        if (id == null || !ValidateUtil.Number(id) || id <= 0) return R.failureRequestParam().msg("id格式不正确");
        // 执行回收操作 0默认 1回收

//        Long userId = 1371387567439171585L;
        ColumnPO columnPO = new ColumnPO();
        columnPO.setId(id);
        columnPO.setModifierId(userId);
        columnPO.setRecovery(1);
        boolean result = columnService.updateById(columnPO);
        if (!result) return R.failure().msg("回收失败");

        // TODO:: 回收栏目的菜单权限
        ArrayList<Long> longs = new ArrayList<>();
        longs.add(id);
        boolean removeSitePermission = cmsMenuService.removeColumnPermission(longs);
        if (!removeSitePermission) return R.failure().msg("回收失败");

        return R.success().msg("回收成功");
    }

    @SitePermission({REMOVE_BY_IDS})
    @Transactional
    @ApiOperation(value = "根据id批量回收栏目", notes = "根据id批量回收栏目")
    @PutMapping("/remove-by-ids")
    public R removeByIds(@ApiParam(value = "站点id之间用英文逗号分隔", required = true, example = "12312313123,12312313123") @RequestParam(required = false) String ids,
                         @RequestAttribute("userId") Long userId) {

        // 校验ids
        if (null == ids || StringUtils.isEmpty(ids)) return R.failureRequestParam().msg("请选择你要的批量回收栏目的id");

        // 将字符串ids进行分割成多个字符串数组idSplit
        String[] idSplit = ids.split(",");
        // 创建一个数组存放idList
        ArrayList<Long> idList = new ArrayList<>();
        // 对字符串数组idSplit循环遍历和转换 因为传进来的id是Long类型的 此时的id是String类型的
        for (String idString : idSplit) {
            Long id = Long.valueOf(idString);
            idList.add(id);
        }

        // 通过改造更新的条件构造器进行批量操作
        ColumnPO columnPO = new ColumnPO();
        UpdateWrapper<ColumnPO> columnPOUpdateWrapper = new UpdateWrapper<>();
        columnPOUpdateWrapper.set("MODIFIER_ID", userId);
        columnPOUpdateWrapper.set("IS_RECOVERY", 1);
        columnPOUpdateWrapper.in("ID", idList);
        boolean result = columnService.update(columnPO, columnPOUpdateWrapper);
        if (!result) R.failure().msg("批量回收失败");

        boolean removeSitePermission = cmsMenuService.removeColumnPermission(idList);
        if (!removeSitePermission) return R.failure().msg("回收失败");

        return R.success().msg("批量回收成功");
    }

    @SitePermission({DETAIL})
    @ApiOperation(value = "根据栏目id获取栏目信息", notes = "根据栏目id获取栏目信息")
    @GetMapping("/get-column-by-id")
    public R<ColumnItemVO> getColumnById(
            @ApiParam(value = "id", required = true, example = "12312313123") @RequestParam(required = false) Long id) {

        // 校验id
        if (id == null || !ValidateUtil.Number(id)) {
            return R.failureRequestParam().msg("栏目id输入有误");
        }
        // 进行根据id查询一个栏目信息
        ColumnPO columnPO = columnService.getById(id);
        // 如果没有查询到对应的栏目信息
        if (columnPO == null) return R.resultCodeMsg(ResultCodeMsgEnum.DATA_NOT_EXIST);
        // 将查询到的对象信息转化为VO
        ColumnItemVO columnItemVO = new ColumnItemVO();
        BeanUtils.copyProperties(columnPO, columnItemVO);

        columnItemVO.setPcTemplateFilePath(columnPO.getPcTemplatePath());
        columnItemVO.setH5TemplateFilePath(columnPO.getH5TemplatePath());

        // 获取父栏目名称
        columnItemVO.setParentId(columnPO.getParentId());
        // 首先判断parentID是否为 0L,如果不是，根据parentId查找父栏目，取出父栏目的name;如果是，就将父栏目名设为顶级栏目
        if (!columnPO.getParentId().equals(0L)) {
            ColumnPO parentColumnPO = columnService.getById(columnPO.getParentId());
            columnItemVO.setParentColumnName(parentColumnPO.getName());

        } else {
            columnItemVO.setParentColumnName("顶级栏目");
        }
        return R.success().data(columnItemVO);

    }

    @SitePermission({UPDATE})
    @ApiOperation(value = "根据栏目id更新栏目信息", notes = "根据栏目id更新栏目信息")
    @PutMapping("/update-column-by-id")
    public R updateColumnById(@ApiParam(value = "站点id", required = true, example = "1435204946847760385") @RequestParam(required = false) Long siteId,
                              @ApiParam(value = "父栏目id（如果是顶级栏目就传Long类型的0）", required = true, example = "1234567890") @RequestParam(required = false) Long parentId,
                              @ApiParam(value = "栏目id", required = true, example = "1234567890") @RequestParam(required = false) Long id,
                              @ApiParam(value = "栏目名称", required = true, example = "关于我们") @RequestParam(required = false) String name,
                              @ApiParam(value = "栏目编码（小写字母和下划线组成）", required = true, example = "ghsc") @RequestParam(required = false) String encoded,
                              @ApiParam(value = "栏目类型（接口获取）", required = true, example = "PIN_DAO_FENG_MIAN") @RequestParam(required = false) String type,
                              @ApiParam(value = "跳转地址", required = false, example = "http://xxx.com/xxx") @RequestParam(required = false) String jumpUrl,
                              @ApiParam(value = "每页条目数", required = false, example = "8") @RequestParam(required = false) Integer pageLimit,
                              @ApiParam(value = "序号", required = false, example = "0") @RequestParam(required = false) Integer sort,
                              @ApiParam(value = "栏目模板pc端(被栏目使用)", required = false, example = "123123123123") @RequestParam(required = false) Long pcTemplateId,
                              @ApiParam(value = "栏目模板h5端(被栏目使用)", required = false, example = "123123123132") @RequestParam(required = false) Long h5TemplateId,
                              @ApiParam(value = "是否在导航中显示 (0否，1是)", required = true, example = "1") @RequestParam(required = false) Integer nav,
                              @ApiParam(value = "PC端模板路径(被栏目使用)", required = false, example = "1") @RequestParam(required = false) String pcTemplateFilePath,
                              @ApiParam(value = "H5端模板路径(被栏目使用)", required = false, example = "1") @RequestParam(required = false) String h5TemplateFilePath,
                              @ApiParam(value = "栏目logo(地址)", required = false, example = "E://11.jpg") @RequestParam(required = false) String logo,
                              @RequestAttribute("userId") Long userId) {

        //h5TemplatePath
        // 数据校验
        if (null == id || !ValidateUtil.Number(id) || id <= 0) return R.failureRequestParam().msg("栏目id为空或格式不正确");
        if (null == parentId || !ValidateUtil.Number(parentId)) return R.failureRequestParam().msg("父栏目id为空或格式不正确");
        if (StringUtils.isEmpty(name)) return R.failureRequestParam().msg("栏目名称为空或空字符串");
        // 站点id校验
        if (null == siteId || !ValidateUtil.Number(siteId) || siteId < 0) return R.failure().msg("id格式不正确");

        // 检验格式，是小写字母和下划线组成的才符合要求
        if (!ValidateUtil.LetterINumber(encoded)) return R.failureRequestParam().msg("栏目编码只能为小写字母和下划线的组合");

        // 栏目编码校验，格式正确就继续，格式不正确返回提示信息
        Boolean checkResult = columnService.checkColumnEncoded(siteId, parentId, id, encoded);
        if (!checkResult) return R.failureRequestParam().msg("栏目编码重复");

        if (StringUtils.isEmpty(type)) return R.failureRequestParam().msg("栏目类型不能为空");
        if (nav == null || !ValidateUtil.Number(nav)) return R.failureRequestParam().msg("必须指定是否在导航中显示");

        ColumnPO columnPO = new ColumnPO();
        columnPO.setId(id);
        columnPO.setName(name);
        columnPO.setParentId(parentId);

        // 维护xpath和encodedXpath
        String encodedXpath = "/" + encoded;
        // 如果parentId是0
        if (parentId.equals(0L)) {
            columnPO.setXpath("0");
            columnPO.setEncodedXpath(encodedXpath);
        } else {
            // 如果parentId不是0
            ColumnPO columnPOById = columnService.getById(parentId);
            if (columnPOById != null) {
                columnPO.setXpath(columnPOById.getXpath() + "-" + parentId);
                columnPO.setEncodedXpath(columnPOById.getEncodedXpath() + encodedXpath);
            }
        }

        if (sort != null && ValidateUtil.Number(sort)) columnPO.setSort(sort);
        columnPO.setEncoded(encoded);
        if (StringUtils.isNotEmpty(type)) columnPO.setType(type);

        columnPO.setModifierId(userId);
        // 设置pc端模板
        if (pcTemplateId != null && ValidateUtil.Number(pcTemplateId) && pcTemplateId > 0)
            columnPO.setPcTemplateId(pcTemplateId);
        // 设置h5端模板
        if (h5TemplateId != null && ValidateUtil.Number(h5TemplateId) && h5TemplateId > 0)
            columnPO.setPcTemplateId(h5TemplateId);

        columnPO.setPcTemplatePath(pcTemplateFilePath);
        columnPO.setH5TemplatePath(h5TemplateFilePath);
        columnPO.setNav(nav);
        columnPO.setLogo(logo);
        columnPO.setJumpUrl(jumpUrl);
        columnPO.setPageLimit(pageLimit);

        Boolean updateResult = columnService.updateById(columnPO);
        if (updateResult) return R.success().msg("更新成功");
        return R.failure().msg("更新失败");
    }

    @SitePermission({RECOVERY_BY_ID})
    @ApiOperation(value = "根据id恢复栏目", notes = "根据id恢复栏目")
    @PutMapping("/recovery-by-id")
    public R recoveryById(
            @ApiParam(value = "id", required = true, example = "12312313123") @RequestParam(required = false) Long id,
            @RequestAttribute("userId") Long userId) {

        // 校验id
        if (id == null || !ValidateUtil.Number(id) || id <= 0) return R.failure().msg("id格式不正确");

        // TODO:: 打包时userId要注释
//        Long userId = 1371387567439171585L;

        // 执行恢复操作 0默认 1回收
        ColumnPO columnPO = new ColumnPO();
        columnPO.setModifierId(userId);
        columnPO.setId(id);
        columnPO.setRecovery(0);
        boolean result = columnService.updateById(columnPO);

        if (result) return R.success().msg("恢复成功");
        return R.failure().msg("恢复失败");
    }

    @SitePermission({RECOVERY_BY_IDS})
    @ApiOperation(value = "根据id批量恢复栏目", notes = "根据id批量恢复栏目")
    @PutMapping("/recovery-by-ids")
    public R recoveryByIds(
            @ApiParam(value = "站点id之间用英文逗号分隔", required = true, example = "12312313123,12312313123") @RequestParam(required = false) String ids,
            @RequestAttribute("userId") Long userId) {

        // 校验ids
        if (null == ids || StringUtils.isEmpty(ids)) return R.failureRequestParam().msg("请选择你要恢复的站点id");
        // 先把字符串ids分割成数组idSplit
        String[] idSplit = ids.split(",");
        // 因为id是Long类型的 所以创建一个数组存放
        ArrayList<Long> idList = new ArrayList<>();
        // 对idSplit进行遍历 idSplit转换成Long类型的 添加到idList中
        for (String idString : idSplit) {
            Long id = Long.valueOf(idString);
            idList.add(id);
        }
        // TODO:: 打包时userId要注释
//        Long userId = 1371387567439171585L;

        // 执行恢复操作
        ColumnPO columnPO = new ColumnPO();
        UpdateWrapper<ColumnPO> columnPOUpdateWrapper = new UpdateWrapper<>();
        columnPOUpdateWrapper.set("MODIFIER_ID", userId);
        columnPOUpdateWrapper.set("IS_RECOVERY", 0);
        columnPOUpdateWrapper.in("ID", idList);
        boolean result = columnService.update(columnPO, columnPOUpdateWrapper);

        if (result) return R.success().msg("批量恢复成功");
        return R.failure().msg("批量恢复失败");
    }

    @SitePermission({GET_COLUMN_ARTICLE_MODEL_BY_COLUMN_ID})
    @ApiOperation(value = "根据栏目id获取栏目关联文章模型信息", notes = "根据栏目id获取栏目关联文章模型信息")
    @GetMapping("/get-column-article-model-by-column-id")
    public R<ColumnAtricleModelVO> getColumnArticleModelByColumnId(
            @ApiParam(value = "columnId", required = true, example = "12312313123") @RequestParam(required = false) Long columnId) {

        // 校验columnId
        if (columnId == null || !ValidateUtil.Number(columnId)) return R.failureRequestParam().msg("栏目id输入有误");

        // 创建要返回的VO对象
        ColumnAtricleModelVO columnAtricleModelVO = new ColumnAtricleModelVO();

        // 根据columnId查询一个文章模型信息
        QueryWrapper<ColumnArticleModelPO> columnArticleModelPOQueryWrapper = new QueryWrapper<>();
        columnArticleModelPOQueryWrapper.eq("COLUMN_ID", columnId);
        ColumnArticleModelPO columnArticleModelPO = columnArticleModelService.getOne(columnArticleModelPOQueryWrapper);

        // 如果没有查到一个对象 就设置默认值
        columnAtricleModelVO.setArticleModelId(0L);
        columnAtricleModelVO.setArticleModelName("");
        columnAtricleModelVO.setH5TemplateId(0L);
        columnAtricleModelVO.setH5TemplateName("");
        columnAtricleModelVO.setPcTemplateId(0L);
        columnAtricleModelVO.setPcTemplateName("");

        // 如果有查到一个对象
        if (columnArticleModelPO != null) {
            // 将查询到的对象信息转化为VO
            BeanUtils.copyProperties(columnArticleModelPO, columnAtricleModelVO);

            // 查询文章模型名称
            ArticleModelPO articleModelPO = articleModelService.getById(columnArticleModelPO.getArticleModelId());
            if (articleModelPO != null) columnAtricleModelVO.setArticleModelName(articleModelPO.getName());

            // 查询PC模板名称
            if (null != columnArticleModelPO.getPcTemplateFilePath()) {
                String[] split = columnArticleModelPO.getPcTemplateFilePath().split("/");
                columnAtricleModelVO.setPcTemplateName(split[split.length - 1]);
            }

            // 查询H5模板名称
            if (null != columnArticleModelPO.getH5TemplateFilePath()) {
                String[] split = columnArticleModelPO.getH5TemplateFilePath().split("/");
                columnAtricleModelVO.setH5TemplateName(split[split.length - 1]);
            }
        }
        // 返回最终的VO对象
        return R.success().data(columnAtricleModelVO);
    }

    @SitePermission({SAVE_OR_UPDATE_COLUMN_ARTICLE_MODEL_BY_COLUMN_ID})
    @ApiOperation(value = "根据栏目id新增或者更新栏目关联文章模型信息", notes = "根据栏目id新增或者更新栏目关联文章模型信息")
    @PutMapping("/save-or-update-column-article-model-by-column-id")
    public R saveOrUpdateColumnArticleModelByColumnId(
            @ApiParam(value = "栏目id", required = true, example = "12312313123") @RequestParam(required = false) Long columnId,
            @ApiParam(value = "文章模型id", required = true, example = "12312313123") @RequestParam(required = false) Long articleModelId,
            @ApiParam(value = "栏目文章模型pc端", required = false, example = "213123123123") @RequestParam(required = false) Long pcTemplateId,
            @ApiParam(value = "栏目文章模型h5端", required = false, example = "123123123123") @RequestParam(required = false) Long h5TemplateId,
            @ApiParam(value = "PC模板文件路径", required = false, example = "D://upload//pc") @RequestParam(required = false) String pcTemplateFilePath,
            @ApiParam(value = "H5模板文件路径", required = false, example = "D://upload//pc") @RequestParam(required = false) String h5TemplateFilePath,
            @RequestAttribute("userId") Long userId) {

        // 进行根据id查询一个文章模型信息
        QueryWrapper<ColumnArticleModelPO> columnArticleModelPOQueryWrapper = new QueryWrapper<>();
        columnArticleModelPOQueryWrapper.eq("COLUMN_ID", columnId);
        ColumnArticleModelPO columnArticleModelPO = columnArticleModelService.getOne(columnArticleModelPOQueryWrapper);

        boolean result = true;
        // 判断PO是否为null
        if (columnArticleModelPO != null) {
            // 如果columnId存在文章模型记录 则进行更新操作
            columnArticleModelPO.setArticleModelId(articleModelId);
            columnArticleModelPO.setPcTemplateId(pcTemplateId);
            columnArticleModelPO.setH5TemplateId(h5TemplateId);
            columnArticleModelPO.setModifierId(userId);
            columnArticleModelPO.setH5TemplateFilePath(h5TemplateFilePath);
            columnArticleModelPO.setPcTemplateFilePath(pcTemplateFilePath);
            UpdateWrapper<ColumnArticleModelPO> columnArticleModelPOUpdateWrapper = new UpdateWrapper<>();
            columnArticleModelPOUpdateWrapper.eq("COLUMN_ID", columnId);

            result = columnArticleModelService.update(columnArticleModelPO, columnArticleModelPOUpdateWrapper);

        } else {
            // 如果没有查到一个对象 则进行新增操作
            ColumnArticleModelPO columnArticleModelCreatePO = new ColumnArticleModelPO();
            columnArticleModelCreatePO.setArticleModelId(articleModelId);
            columnArticleModelCreatePO.setH5TemplateId(h5TemplateId);
            columnArticleModelCreatePO.setPcTemplateId(pcTemplateId);
            columnArticleModelCreatePO.setColumnId(columnId);
            columnArticleModelCreatePO.setModifierId(userId);
            columnArticleModelCreatePO.setCreatorId(userId);
            columnArticleModelCreatePO.setH5TemplateFilePath(h5TemplateFilePath);
            columnArticleModelCreatePO.setPcTemplateFilePath(pcTemplateFilePath);

            result = columnArticleModelService.save(columnArticleModelCreatePO);
        }

        if (result) return R.success().msg("操作成功");
        return R.failure().msg("操作失败");
    }

    @SitePermission({COLUMN_PAGE})
    @ApiOperation(value = "查询子栏目列表", notes = "查询子栏目列表")
    @GetMapping("/get-child-column-by-parent-column-id")
    public R<ColumnPageListVO> getChildColumnByParentColumnId(@ApiParam(value = "站点id", required = true, example = "1234567890") @RequestParam(required = false) Long siteId,
                                                              @ApiParam(value = "父级栏目id（如果是顶级栏目就传Long类型的0）", required = true, example = "关于我们") @RequestParam(required = false) Long parentId,
                                                              @ApiParam(value = "栏目名称", required = false, example = "关于我们1") @RequestParam(required = false) String name,
                                                              @ApiParam(value = "类型(固定为五种类型：频道封面:PIN_DAO_FENG_MIAN、列表:LIE_BIAO、站点首页:ZHAN_DIAN_SHOU_YE、分页列表FEN_YE_LIE_BIAO、跳转链接TIAO_ZHUAN_LIAN_JIE)", required = false, example = "LIE_BIAO") @RequestParam(required = false) String type,
                                                              @ApiParam(value = "是否显示在导航栏中，0否，1是", required = false, example = "1") @RequestParam(required = false) Integer nav,
                                                              @ApiParam(value = "更新人", required = false, example = "张正铭") @RequestParam(required = false) String modifierName,
                                                              @ApiParam(value = "根据更新时间搜索的开始时间（10位时间戳）", required = false, example = "1234567891") @RequestParam(required = false) Date gmtModifiedStart,
                                                              @ApiParam(value = "根据更新时间搜索的结束时间（10位时间戳）", required = false, example = "1231231231") @RequestParam(required = false) Date gmtModifiedEnd,
                                                              @ApiParam(value = "seo关键字(字符串类型用英文逗号隔开)", required = false, example = "厦门,工会,门户") @RequestParam(required = false) String seoKeywords,
                                                              @ApiParam(value = "seo标题", required = false, example = "厦门市工会门户网站") @RequestParam(required = false) String seoTitle,
                                                              @ApiParam(value = "seo描述", required = false, example = "厦门市工会门户网站") @RequestParam(required = false) String seoDesc,
                                                              @ApiParam(value = "要访问的页码", required = true, example = "1") @RequestParam(required = false) Integer page,
                                                              @ApiParam(value = "页面容量", required = true, example = "10") @RequestParam(required = false) Integer limit) {

        // 参数检验
        if (page < 0) return R.failureRequestParam().msg("页码不正确");
        if (limit < 0) return R.failureRequestParam().msg("页面容量不正确");
        if (parentId == null || parentId < 0) return R.failureRequestParam().msg("父栏目id为空或格式不正确");
        if (siteId == null || siteId <= 0) return R.failureRequestParam().msg("站点id为空或格式不正确");
        if (nav != null && !ValidateUtil.Number(nav)) return R.failureRequestParam().msg("表示置顶的数据有误");

        // 返回到前端的数据
        ColumnPageListVO columnPageListVO = new ColumnPageListVO();
        // 查询站点信息
        SitePO sitePO = siteService.getById(siteId);
        // TODO::提示站点不存在的代码位置
        // 如果没有查到站点信息，表明没有对应的站点
        if (sitePO == null) return R.failure().msg("站点不存在");

        // 开始查询
        QueryWrapper<ColumnPO> columnPOQueryWrapper = new QueryWrapper<>();

        // 查询父栏目
        ColumnPO parentColumnPO = null;
        // 如果父栏目id不为0，表示查询的不是顶级站点
        if (!parentId.equals(0L)) {
            // 查询出父栏目的信息，方便在后面加上所属的父栏目名
            parentColumnPO = columnService.getById(parentId);
            if (parentColumnPO == null) return R.failure().msg("父栏目不存在");

            // 加入查询条件，父栏目parentId
            columnPOQueryWrapper.eq("PARENT_ID", parentId);
        } else {
            // 父栏目id为0时,查询的是顶级栏目
            // 1、通过站点id到中间表去查，对应的顶级栏目的集合
            QueryWrapper<SiteColumnPO> siteColumnPOQueryWrapper = new QueryWrapper<>();
            siteColumnPOQueryWrapper.eq("SITE_ID", siteId);
            List<SiteColumnPO> siteColumnPOList = siteColumnService.list(siteColumnPOQueryWrapper);

            // 2、如果站点下没有栏目，
            if (siteColumnPOList.size() == 0) {
                columnPageListVO.setPage(page);
                columnPageListVO.setTotal(0);
                columnPageListVO.setList(new ArrayList<ColumnVO>());
                columnPageListVO.setLimit(limit);
                return R.success().data(columnPageListVO);
            }

            // 3、新建一个集合存储ColumnPO的id
            ArrayList<Long> columnIdList = new ArrayList<>();
            for (SiteColumnPO siteColumnPO : siteColumnPOList) {
                columnIdList.add(siteColumnPO.getColumnId());
            }

            // 4、添加到构造器中
            columnPOQueryWrapper.in("ID", columnIdList);
        }

        // 栏目名
        if (StringUtils.isNotEmpty(name)) columnPOQueryWrapper.like("NAME", name);

        // 栏目类型
        if (StringUtils.isNotEmpty(type)) {
            if (ColumnEnum.CHANNLE_COVER.getType().equals(type) || ColumnEnum.LIST.getType().equals(type) ||
                    ColumnEnum.SITE_INDEX.getType().equals(type)) {
                columnPOQueryWrapper.eq("TYPE", type);
            }
        }

        // 是否置顶
        if (nav != null && ValidateUtil.Number(nav)) columnPOQueryWrapper.eq("IS_NAV", nav);

        // 根据更新人name查询更新人id
        List<UserPO> userPOList = null;
        if (StringUtils.isNotEmpty(modifierName)) {
            QueryWrapper<UserPO> userWrapper = new QueryWrapper<>();
            // userPOQueryWrapper1.select("ID");
            userWrapper.like("NAME", modifierName);
            userPOList = userService.list(userWrapper);
        }

        // 更新人ID
        if (userPOList != null && userPOList.size() > 0) {
            ArrayList<Long> userIdList = new ArrayList<>();
            for (UserPO userPO : userPOList) {
                userIdList.add(userPO.getId());
            }
            columnPOQueryWrapper.in("MODIFIER_ID", userIdList);
        }
        // 当更新人id查询结果为空，但是传入的更新人姓名不为空的时候，表示表中没有对应的操作人，直接返回空集合
        if ((userPOList == null || userPOList.size() == 0) && StringUtils.isNotEmpty(modifierName)) {
            columnPageListVO.setPage(page);
            columnPageListVO.setLimit(limit);
            columnPageListVO.setTotal(0);
            columnPageListVO.setList(new ArrayList<>());
            return R.success().data(columnPageListVO);
        }

        // 判断时间
        if (gmtModifiedStart != null) columnPOQueryWrapper.ge("GMT_MODIFIED", gmtModifiedStart);
        if (gmtModifiedEnd != null) columnPOQueryWrapper.le("GMT_MODIFIED", gmtModifiedEnd);

        columnPOQueryWrapper.eq("IS_RECOVERY", 0);

        // 关键字
        if (StringUtils.isNotEmpty(seoKeywords)) columnPOQueryWrapper.like("SEO_KEYWORDS", seoKeywords);
        // seo标题
        if (StringUtils.isNotEmpty(seoTitle)) columnPOQueryWrapper.like("SEO_TITLE", seoTitle);
        // seo描述
        if (StringUtils.isNotEmpty(seoDesc)) columnPOQueryWrapper.like("SEO_DESC", seoDesc);

        // 根据更新时间倒序排列
        columnPOQueryWrapper.orderByDesc("GMT_MODIFIED");
        columnPOQueryWrapper.orderByAsc("SORT");

        // 开始分页查询
        Page<ColumnPO> columnPOPage = columnService.page(new Page<>(page, limit), columnPOQueryWrapper);

        // 返回给前端的对象
        columnPageListVO.setPage((int) columnPOPage.getCurrent());
        columnPageListVO.setLimit((int) columnPOPage.getSize());
        columnPageListVO.setTotal((int) columnPOPage.getTotal());

        List<ColumnPO> records = columnPOPage.getRecords();
        ArrayList<ColumnVO> columnVOArrayList = new ArrayList<>();
        for (ColumnPO columnPO : records) {
            ColumnVO columnVO = new ColumnVO();
            BeanUtils.copyProperties(columnPO, columnVO);
            // 站点名字
            columnVO.setSiteName(sitePO.getName());

            // 查询更新人
            UserPO userPO = userService.getById(columnPO.getModifierId());
            columnVO.setModifierName(userPO.getName());

            // 栏目类型,返回中文
            if (ColumnEnum.CHANNLE_COVER.getType().equals(columnPO.getType()))
                columnVO.setType(ColumnEnum.CHANNLE_COVER.getName());
            if (ColumnEnum.LIST.getType().equals(columnPO.getType())) columnVO.setType(ColumnEnum.LIST.getName());
            if (ColumnEnum.SITE_INDEX.getType().equals(columnPO.getType()))
                columnVO.setType(ColumnEnum.SITE_INDEX.getName());

            // 如果传入的父栏目id不是0，那么表示查询的是顶级栏目，不设置父栏目的名字
            if (!parentId.equals(0L)) columnVO.setParentColumnName(parentColumnPO.getName());
            columnVOArrayList.add(columnVO);
        }
        columnPageListVO.setList(columnVOArrayList);

        return R.success().data(columnPageListVO);
    }

    @SitePermission({GET_RECOVERY_CHILD_COLUMN_BY_PARENT_COLUMN_ID})
    @ApiOperation(value = "查询栏目下被回收的子栏目列表", notes = "查询栏目下被回收的子栏目列表")
    @GetMapping("/get-recovery-child-column-by-parent-column-id")
    public R<ColumnPageListVO> getRecoveryChildColumnByParentColumnId(@ApiParam(value = "站点id", required = true, example = "1234567890") @RequestParam(required = false) Long siteId,
                                                                      @ApiParam(value = "父级栏目id（如果是顶级栏目就传Long类型的0）", required = true, example = "1234567890") @RequestParam(required = false) Long parentId,
                                                                      @ApiParam(value = "栏目名称", required = false, example = "关于我们1") @RequestParam(required = false) String name,
                                                                      @ApiParam(value = "类型(固定为五种类型：频道封面:PIN_DAO_FENG_MIAN、列表:LIE_BIAO、站点首页:ZHAN_DIAN_SHOU_YE、分页列表FEN_YE_LIE_BIAO、跳转链接TIAO_ZHUAN_LIAN_JIE)", required = false, example = "LIE_BIAO") @RequestParam(required = false) String type,
                                                                      @ApiParam(value = "是否显示在导航栏中，0否，1是", required = false, example = "1") @RequestParam(required = false) Integer nav,
                                                                      @ApiParam(value = "更新人", required = false, example = "张正铭") @RequestParam(required = false) String modifierName,
                                                                      @ApiParam(value = "根据更新时间搜索的开始时间（10位时间戳）", required = false, example = "1234567891") @RequestParam(required = false) Date gmtModifiedStart,
                                                                      @ApiParam(value = "根据更新时间搜索的结束时间（10位时间戳）", required = false, example = "1231231231") @RequestParam(required = false) Date gmtModifiedEnd,
                                                                      @ApiParam(value = "要访问的页码", required = true, example = "1") @RequestParam(required = false) Integer page,
                                                                      @ApiParam(value = "页面容量", required = true, example = "10") @RequestParam(required = false) Integer limit) {

        // 参数检验
        if (page < 0) return R.failureRequestParam().msg("页码不正确");
        if (limit < 0) return R.failureRequestParam().msg("页面容量不正确");
        if (parentId == null || parentId < 0) return R.failureRequestParam().msg("父栏目id为空或格式不正确");
        if (siteId == null || siteId <= 0) return R.failureRequestParam().msg("站点id为空或格式不正确");
        if (nav != null && !ValidateUtil.Number(nav)) return R.failureRequestParam().msg("表示置顶的数据有误");

        // 查询站点信息
        SitePO sitePO = siteService.getById(siteId);
        // 如果没有查到站点信息，表明没有对应的站点
        if (sitePO == null) return R.failure().msg("站点不存在");

        // 返回的前端对象
        ColumnPageListVO columnPageListVO = new ColumnPageListVO();

        // 开始查询
        QueryWrapper<ColumnPO> columnPOQueryWrapper = new QueryWrapper<>();

        ColumnPO parentColumnPO = null;
        // 如果父栏目id不为0，表示查询的不是顶级站点
        if (!parentId.equals(0L)) {
            // 查询出父栏目的信息，方便在后面加上所属的父栏目名
            parentColumnPO = columnService.getById(parentId);
            if (parentColumnPO == null) return R.failure().msg("父栏目不存在");

            // 加入查询条件，父栏目parentId
            columnPOQueryWrapper.eq("PARENT_ID", parentId);
        } else {
            // 父栏目id为0时,查询的是顶级栏目
            // 1、通过站点id到中间表去查，对应的顶级栏目的集合
            QueryWrapper<SiteColumnPO> siteColumnPOQueryWrapper = new QueryWrapper<>();
            siteColumnPOQueryWrapper.eq("SITE_ID", siteId);
            List<SiteColumnPO> siteColumnPOList = siteColumnService.list(siteColumnPOQueryWrapper);

            // 2、如果站点下没有栏目，
            if (siteColumnPOList == null || siteColumnPOList.size() == 0) {
                columnPageListVO.setPage(page);
                columnPageListVO.setTotal(0);
                columnPageListVO.setList(new ArrayList<>());
                columnPageListVO.setLimit(limit);
                return R.success().data(columnPageListVO);
            }
            // 3、如果站点下有栏目，就新建一个集合存储ColumnPO的id
            ArrayList<Long> columnIdList = new ArrayList<>();
            for (SiteColumnPO siteColumnPO : siteColumnPOList) {
                columnIdList.add(siteColumnPO.getColumnId());
            }

            // 4、添加到构造器中
            columnPOQueryWrapper.in("ID", columnIdList);
        }

        // 栏目名
        if (StringUtils.isNotEmpty(name)) columnPOQueryWrapper.like("NAME", name);

        // 栏目类型
        if (StringUtils.isNotEmpty(type)) {
            columnPOQueryWrapper.eq("TYPE", type);
        }

        // 是否置顶
        if (nav != null && ValidateUtil.Number(nav)) columnPOQueryWrapper.eq("IS_NAV", nav);
        // 根据更新人name查询更新人id
        List<UserPO> userPOList = null;
        if (StringUtils.isNotEmpty(modifierName)) {
            QueryWrapper<UserPO> userWrapper = new QueryWrapper<>();
            // userPOQueryWrapper1.select("ID");
            userWrapper.like("NAME", modifierName);
            userPOList = userService.list(userWrapper);
        }
        // 更新人ID
        if (userPOList != null && userPOList.size() > 0) {
            ArrayList<Long> userIdList = new ArrayList<>();
            for (UserPO userPO : userPOList) {
                userIdList.add(userPO.getId());
            }
            columnPOQueryWrapper.in("MODIFIER_ID", userIdList);
        }

        if ((userPOList == null || userPOList.size() == 0) && StringUtils.isNotEmpty(modifierName)) {
            columnPageListVO.setPage(page);
            columnPageListVO.setLimit(limit);
            columnPageListVO.setTotal(0);
            columnPageListVO.setList(new ArrayList<>());
            return R.success().data(columnPageListVO);
        }

        // 判断时间
        if (gmtModifiedStart != null) columnPOQueryWrapper.ge("GMT_MODIFIED", gmtModifiedStart);
        if (gmtModifiedEnd != null) columnPOQueryWrapper.le("GMT_MODIFIED", gmtModifiedEnd);

        columnPOQueryWrapper.eq("IS_RECOVERY", 1);
        // 根据更新时间倒序排列
        columnPOQueryWrapper.orderByDesc("GMT_MODIFIED");
        columnPOQueryWrapper.orderByAsc("SORT");
        // 开始分页查询
        Page<ColumnPO> columnPOPage = columnService.page(new Page<>(page, limit), columnPOQueryWrapper);

        // 返回给前端的对象
        columnPageListVO.setPage((int) columnPOPage.getCurrent());
        columnPageListVO.setLimit((int) columnPOPage.getSize());
        columnPageListVO.setTotal((int) columnPOPage.getTotal());

        List<ColumnPO> records = columnPOPage.getRecords();
        ArrayList<ColumnVO> columnVOArrayList = new ArrayList<>();
        for (ColumnPO columnPO : records) {
            ColumnVO columnVO = new ColumnVO();
            BeanUtils.copyProperties(columnPO, columnVO);
            // 站点名字
            columnVO.setSiteName(sitePO.getName());

            // 更新人姓名
            UserPO userPO = userService.getById(columnPO.getModifierId());
            columnVO.setModifierName(userPO.getName());

            // 栏目类型，返回中文
            if (ColumnEnum.CHANNLE_COVER.getType().equals(columnPO.getType()))
                columnVO.setType(ColumnEnum.CHANNLE_COVER.getName());
            if (ColumnEnum.LIST.getType().equals(columnPO.getType())) columnVO.setType(ColumnEnum.LIST.getName());
            if (ColumnEnum.SITE_INDEX.getType().equals(columnPO.getType()))
                columnVO.setType(ColumnEnum.SITE_INDEX.getName());

            // 如果父栏目id不为0，那么就设置子栏目的父栏目名称；如果父栏目id为0那么就不设置父栏目名称
            if (!parentId.equals(0L)) columnVO.setParentColumnName(parentColumnPO.getName());
            columnVOArrayList.add(columnVO);
        }
        columnPageListVO.setList(columnVOArrayList);

        return R.success().data(columnPageListVO);
    }

    @SitePermission({UPDATE_VERIFY_STATUS_BY_COLUMN_ID})
    @ApiOperation(value = "根据栏目id修改是否需要审核", notes = "根据栏目id修改是否需要审核")
    @PutMapping("/update-verify-status-by-column-id")
    public R updateVerifyStatusByColumnId(@ApiParam(value = "栏目id", required = true, example = "1440511661143220226") @RequestParam(required = false) Long columnId,
                                          @ApiParam(value = "是否需要审核(0不需要,1需要审核)", required = true, example = "1") @RequestParam(required = false) Integer verifyStatus) {

        // 参数校验
        if (null == columnId || !ValidateUtil.Number(columnId) || columnId <= 0)
            return R.failureRequestParam().msg("栏目id为空或格式不正确");
        if (null == verifyStatus || !ValidateUtil.Number(verifyStatus) || verifyStatus < 0)
            return R.failureRequestParam().msg("请传入正确的审核编号");

        // TODO:: 打包时userId要注释
//        Long userId = 1371387567439171585L;

        // 根据传入的审核参数修改审核状态
        ColumnPO columnPO = new ColumnPO();
        UpdateWrapper<ColumnPO> columnPOUpdateWrapper = new UpdateWrapper<>();
        columnPOUpdateWrapper.eq("ID", columnId);
        columnPOUpdateWrapper.set("VERIFY_STATUS", verifyStatus);

        boolean result = columnService.update(columnPO, columnPOUpdateWrapper);
        return R.success().msg("根据栏目id修改是否需要审核成功");

    }


    @ApiOperation(value = "栏目logo上传", notes = "栏目logo上传")
    @PostMapping("/upload-logo")
    public R<ImageFileNameVO> uploadLogo(
            @ApiParam(value = "file", required = true, example = "1") @RequestParam(required = false) MultipartFile file) throws IOException {

        // 校验上传文件是否为空
        if (null == file) return R.failureRequestParam().msg("logo文件参数为空");

        // file.getOriginalFilename()得到上传时的文件名(仅返回文件名,并不会包含路径) 并校验是否是图片
        if (!ValidateUtil.isPicture(file.getOriginalFilename())) return R.failureRequestParam().msg("该文件不是图片");

        // file.getSize()以字节为单位返回指定文件的大小
        if (file.getSize() > FileConst.UPLOAD_LOGO_PICTURE_SIZE)
            return R.failureRequestParam().msg("图片大小不能超过" + FileConst.UPLOAD_LOGO_PICTURE_SIZE + "M");
        String fileUrl = fastdfsFileService.uploadSiteLogo(file);

        // 失败
        if (null == fileUrl) return R.failure();

        // 返回文件路径
        ImageFileNameVO imageFileNameVO = new ImageFileNameVO();
        imageFileNameVO.setFileUrl(fileUrl);
        return R.success().data(imageFileNameVO);
    }


    @ApiOperation(value = "预览PC端栏目页渲染内容", notes = "预览PC端栏目页渲染内容")
    @GetMapping("/get-pc-template-render-content")
    public R<String> getPCTemplateRenderContent(@ApiParam(value = "站点id", required = true, example = "123456789") @RequestParam(required = false) Long siteId,
                                                @ApiParam(value = "栏目id", required = true, example = "123456789") @RequestParam(required = false) Long columnId) {
        // 参数校验
        if (siteId == null || !ValidateUtil.Number(siteId) || siteId <= 0)
            return R.failureRequestParam().msg("站点id不能为空");

        // 参数校验
        if (columnId == null || !ValidateUtil.Number(columnId) || columnId <= 0)
            return R.failureRequestParam().msg("栏目id不能为空");

        QueryWrapper<StaticLogPO> staticLogPOQueryWrapper = new QueryWrapper<>();
        staticLogPOQueryWrapper.eq("SITE_ID", siteId);
        staticLogPOQueryWrapper.eq("COLUMN_ID", columnId);
        staticLogPOQueryWrapper.eq("STATUS", StaticHtmlStatusEnum.JIN_XING_ZHONG.getValue());
        staticLogPOQueryWrapper.eq("STATIC_TYPE", StaticHtmlTypeEnum.COLUMN.getValue());
        StaticLogPO staticLogPO = staticLogService.getOne(staticLogPOQueryWrapper, false);
        if (null != staticLogPO && null != staticLogPO.getId()) {
            return R.failure().msg("静态化任务正在进行,请稍后再试!");
        }

        // 查询站点信息
        SitePO sitePO = siteService.getById(siteId);
        if (ValidateUtil.isNullOrEmpty(sitePO)) return R.resultCodeMsg(ResultCodeMsgEnum.DATA_NOT_EXIST);

        // 查询栏目信息
        QueryWrapper<ColumnPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", columnId);
        queryWrapper.eq("IS_RECOVERY", 0);
        ColumnPO columnPO = columnService.getOne(queryWrapper, false);
        // 如果栏目为空，直接返回
        if (ValidateUtil.isNullOrEmpty(columnPO)) return R.success();

        // 如果不为空就要准备生成--------站点的静态文件存储路径
        String storageStaticPath = siteService.getStorageStaticPath(sitePO.getId());
        // 静态文件存储路径-----到pc
        String pcStorageStaticPath = storageStaticPath + File.separator + "pc";

        // 拷贝到预览目录下
        // 1、静态文件
        File previewStaticFile = FileUtil.file(previewPath + File.separator + "static");
        File sourceStaticFile = FileUtil.file( pcStorageStaticPath + File.separator + "static");
        FileUtil.copyContent(sourceStaticFile, previewStaticFile, true);
        // 2、静态化页面
        File previewHtmlFile = FileUtil.file(previewPath + columnPO.getEncodedXpath());
        File sourceHtmlFile = FileUtil.file(pcStorageStaticPath + columnPO.getEncodedXpath());
        FileUtil.copyContent(sourceHtmlFile, previewHtmlFile, true);

        String previewColumn = generateUrl(sitePO, columnPO);

        return R.success().data(previewColumn);
    }


    /**
     * 获取预览的链接
     * @param sitePO
     * @param columnPO
     * @return
     */
    private String generateUrl(SitePO sitePO, ColumnPO columnPO) {

        // 判断栏目下是否有子栏目,有子栏目就生成栏目列表页面，没有子栏目就生成文章列表页面（PS：栏目列表页面，包含了文章列表页面）
        QueryWrapper<ColumnPO> columnQueryWrapper = new QueryWrapper<>();
        columnQueryWrapper.eq("parent_id", columnPO.getId());
        columnQueryWrapper.eq("is_recovery", 0);
        List<ColumnPO> childColumnPOList = columnService.list(columnQueryWrapper);
        String previewColumn = "";

        // 有子栏目
        if (childColumnPOList != null && childColumnPOList.size() > 0) {
            for (ColumnPO childColumnPO : childColumnPOList) {
                int page = 1;
                int limit = 15;
                int total = 0;

                if (ColumnEnum.PAGE_LIST.getType().equals(columnPO.getType())) {
                    // 查询该栏目下总共有多少已发布文章
                    QueryWrapper<ArticlePO> articlePOQueryWrapper = new QueryWrapper<>();
                    articlePOQueryWrapper.eq("COLUMN_ID", childColumnPO.getId());
                    articlePOQueryWrapper.eq("ARTICLE_STATUS", ArticleEnum.STATUS_YI_FA_BU.getValue());
                    articlePOQueryWrapper.eq("IS_RECOVERY", 0);
                    total = articleService.count(articlePOQueryWrapper);

                    // 每页显示的条目数
                    if (total == 0) {
                        page = 1;
                    } else {
                        limit = childColumnPO.getPageLimit();
                        if (limit == 0) limit = 15;
                        page = (int) Math.ceil(total / limit);
                    }
                }
                for (int i = 1; i <= page; i++) {
                    // 获取栏目的静态文件存储信息
                    if (page == 1) {
                        previewColumn = previewUrl + childColumnPO.getEncodedXpath()  + "/index.html";
                    } else {
                        previewColumn = previewUrl + childColumnPO.getEncodedXpath() + "/index_" + i + ".html";
                    }
                }
            }
            return previewColumn;
        } else {
            // 生成文章列表页面
            // 首页
            if (columnPO.getType().equals(ColumnEnum.SITE_INDEX.getType())) {
                return sitePO.getDomainUrl() + "/index.html";
            }

            // 没有子栏目，生成文章列表页面
            int page = 1;
            int limit = 15;
            int total = 0;
            if (ColumnEnum.PAGE_LIST.getType().equals(columnPO.getType())) {
                // 查询该栏目下总共有多少已发布文章
                QueryWrapper<ArticlePO> articlePOQueryWrapper = new QueryWrapper<>();
                articlePOQueryWrapper.eq("COLUMN_ID", columnPO.getId());
                articlePOQueryWrapper.eq("ARTICLE_STATUS", ArticleEnum.STATUS_YI_FA_BU.getValue());
                articlePOQueryWrapper.eq("IS_RECOVERY", 0);
                total = articleService.count(articlePOQueryWrapper);

                // 每页显示的条目数
                if (total == 0) {
                    page = 1;
                } else {
                    limit = columnPO.getPageLimit();
                    if (limit == 0) limit = 15;
                    page = (int) Math.ceil(total / limit);
                }
            }
            for (int i = 1; i <= page; i++) {
                // 获取栏目的静态文件存储信息
                if (page == 1) {
                    previewColumn = previewUrl + columnPO.getEncoded() + "/index.html";
                } else {
                    previewColumn = previewUrl + columnPO.getEncoded() + "/index_" + i + ".html";
                }

            }
            return previewColumn;
        }

    }


    @ApiOperation(value = "预览H5端栏目页渲染内容", notes = "预览H5端栏目页渲染内容")
    @GetMapping("/get-h5-template-render-content")
    public R<String> getH5TemplateRenderContent(@ApiParam(value = "站点id", required = true, example = "123456789") @RequestParam(required = false) Long siteId,
                                                @ApiParam(value = "栏目id", required = true, example = "123456789") @RequestParam(required = false) Long columnId) {
        // 参数校验
        if (siteId == null || !ValidateUtil.Number(siteId) || siteId <= 0)
            return R.failureRequestParam().msg("站点id不能为空");

        // 参数校验
        if (columnId == null || !ValidateUtil.Number(columnId) || columnId <= 0)
            return R.failureRequestParam().msg("栏目id不能为空");

        QueryWrapper<StaticLogPO> staticLogPOQueryWrapper = new QueryWrapper<>();
        staticLogPOQueryWrapper.eq("SITE_ID", siteId);
        staticLogPOQueryWrapper.eq("COLUMN_ID", columnId);
        staticLogPOQueryWrapper.eq("STATUS", StaticHtmlStatusEnum.JIN_XING_ZHONG.getValue());
        staticLogPOQueryWrapper.eq("STATIC_TYPE", StaticHtmlTypeEnum.COLUMN.getValue());
        StaticLogPO staticLogPO = staticLogService.getOne(staticLogPOQueryWrapper, false);
        if (null != staticLogPO && null != staticLogPO.getId()) {
            return R.failure().msg("静态化任务正在进行,请稍后再试!");
        }

        // 查询站点信息
        SitePO sitePO = siteService.getById(siteId);
        if (ValidateUtil.isNullOrEmpty(sitePO)) return R.resultCodeMsg(ResultCodeMsgEnum.DATA_NOT_EXIST);

        // 查询栏目信息
        QueryWrapper<ColumnPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", columnId);
        queryWrapper.eq("IS_RECOVERY", 0);
        ColumnPO columnPO = columnService.getOne(queryWrapper, false);
        // 如果栏目为空，直接返回
        if (ValidateUtil.isNullOrEmpty(columnPO)) return R.success();

        // 如果不为空就要准备生成--------站点的静态文件存储路径
        String storageStaticPath = siteService.getStorageStaticPath(sitePO.getId());
        // 静态文件存储路径-----到pc
        String pcStorageStaticPath = storageStaticPath + File.separator + "pc" + File.separator + "h5";

        // 拷贝到预览目录下
        // 1、静态文件
        File previewStaticFile = FileUtil.file(previewPath  + File.separator + "h5" + File.separator + "static");
        File sourceStaticFile = FileUtil.file( pcStorageStaticPath + File.separator + "static");
        FileUtil.copyContent(sourceStaticFile, previewStaticFile, true);
        // 2、静态化页面
        File previewHtmlFile = FileUtil.file(previewPath + File.separator + "h5" + columnPO.getEncodedXpath());
        File sourceHtmlFile = FileUtil.file(pcStorageStaticPath + columnPO.getEncodedXpath());
        FileUtil.copyContent(sourceHtmlFile, previewHtmlFile, true);

        String previewColumn = generateUrl(sitePO, columnPO);

        return R.success().data(previewColumn);
    }



    @ApiOperation(value = "合并栏目", notes = "合并栏目")
    @PostMapping("/merge-columns")
    public R mergeColumns(@ApiParam(value = "当前栏目id", required = true, example = "112345675646") @RequestParam(required = false) Long columnId,
                          @ApiParam(value = "被选中的栏目ids", required = true, example = "112345675646") @RequestParam(required = false) String selectedColumnIds,
                          @ApiParam(value = "合并后的文章状态(CAO_GAO(草稿)YI_FA_BU(已发布)YUAN_ZHUANG_TAI(原状态))", required = true, example = "CAO_GAO") @RequestParam(required = false) String articleMergeStatus,
                          @ApiParam(value = "操作选项(NO_RESERVED_COLUMN(不保留)RESERVED_COLUMN(保留))", required = true, example = "NO_RESERVED_COLUMN") @RequestParam(required = false) String choice,
                          @RequestAttribute("userId") Long userId) {

        // 参数校验
        if (null == columnId || !ValidateUtil.Number(columnId) || columnId <= 0) return R.failureRequestParam().msg("栏目id为空或格式不正确");
        if (null == selectedColumnIds || StringUtils.isEmpty(selectedColumnIds)) return R.failureRequestParam().msg("请选择你要合并的栏目id");
        if (StringUtils.isEmpty(articleMergeStatus)) return R.failureRequestParam().msg("合并的文章状态不能为空");
        if (StringUtils.isEmpty(choice)) return R.failureRequestParam().msg("操作选项不能为空");

        // 1、先将栏目字符串ids分割成一个数组->columnSplit
        String[] split = selectedColumnIds.split(",");
        // 因为id是Long类型的 创建一个数组存放
        ArrayList<Long> columnIdList = new ArrayList<>();
        // 对split进行遍历->split(String)转换成Long类型的 放到columnList中
        for (String columnSplit : split) {
            Long columnIdLong = Long.valueOf(columnSplit);
            columnIdList.add(columnIdLong);
        }

        // 2、根据被选栏目id 获取该栏目下的所有文章
        QueryWrapper<ArticlePO> articlePOQueryWrapper = new QueryWrapper<>();
        articlePOQueryWrapper.in("COLUMN_ID", columnIdList);
        List<ArticlePO> articlePOList = articleService.list(articlePOQueryWrapper);

        // 遍历 得到每一个文章的id 并查出该文章的拓展表信息、附件信息、相关文章信息等 并复制
        for (ArticlePO article : articlePOList) {
            Boolean copyArticle = p_copyArticle(article, columnId, articleMergeStatus, userId);
            if (!copyArticle) {
                return R.failure().msg("合并失败");
            }
            article.setRecovery(1);
            article.setModifierId(userId);
            article.setGmtModified(null);
        }

        // 复制文章以后，根据操作选项决定是否保留原栏目
        // 不保留,既回收 NO_RESERVED_COLUMN
        if (choice.equals("NO_RESERVED_COLUMN")) {
            UpdateWrapper<ColumnPO> columnPOUpdateWrapper = new UpdateWrapper<>();
            columnPOUpdateWrapper.set("IS_RECOVERY", 1);
            columnPOUpdateWrapper.in("ID", columnIdList);
//            columnPOUpdateWrapper.lambda().in(ColumnPO::getId, columnIdList);
            boolean result = columnService.update(columnPOUpdateWrapper);
            if (!result) return R.failure().msg("回收原栏目失败！");

            boolean updateBatchById = articleService.updateBatchById(articlePOList);
            if (!updateBatchById) {
                return R.failure().msg("回收栏目下的文章失败！");
            }
        }
        return R.success().msg("合并完成");
    }


    // 复制单篇文章时 1.更改文章此时的columnId  2.更改文章的状态
    private Boolean p_copyArticle(ArticlePO article, Long columnId, String articleMergeStatus, Long userId) {
        // 原本的文件
        ArticlePO articleOriginalPO = article;
        // 复制后的文件名
        String copyTitle = articleOriginalPO.getTitle();

        // 复制后的articleId      设置合并后的文章的状态                                                                          将栏目id设置成合并后的columnId
        Long copyArticleId = articleService.mergeArticle(article.getArticleStatus(), articleMergeStatus, articleOriginalPO.getSiteId(), columnId, copyTitle, articleOriginalPO.getAttribute(), articleOriginalPO.getType(), articleOriginalPO.getReleaseChannel(),
                articleOriginalPO.getOrigin(), articleOriginalPO.getAuthor(), articleOriginalPO.getReleaseTime(), articleOriginalPO.getGmtAnnouncementStart(), articleOriginalPO.getGmtAnnouncementEnd(),
                articleOriginalPO.getCover(), articleOriginalPO.getCoverType(), articleOriginalPO.getSummary(), articleOriginalPO.getId(), articleOriginalPO.getSortType(), userId);
        if (null == copyArticleId) return false;
        // 2、查询出文章id对应的扩展表的信息
        QueryWrapper<ArticleExtendPO> articleExtendPOQueryWrapper = new QueryWrapper<>();
        articleExtendPOQueryWrapper.eq("ARTICLE_ID", article.getId());
        ArticleExtendPO articleExtendPO = articleExtendService.getOne(articleExtendPOQueryWrapper);
        // 复制扩展表信息
        if (!ValidateUtil.isNullOrEmpty(articleExtendPO)) {
            articleExtendService.saveOrUpdateArticleExtend(copyArticleId, articleExtendPO.getContent(), articleExtendPO.getSeoTitle(),
                    articleExtendPO.getSeoKeywords(), articleExtendPO.getSeoDesc(), articleExtendPO.getExtendFieldList(), userId);
        }
        // 获取附件信息
        QueryWrapper<ArticleAttachmentPO> articleAttachmentPOQueryWrapper = new QueryWrapper<>();
        articleAttachmentPOQueryWrapper.eq("ARTICLE_ID", article.getId());
        List<ArticleAttachmentPO> articleAttachmentPOList = articleAttachmentService.list(articleAttachmentPOQueryWrapper);
        // 复制附件信息
        if (!ValidateUtil.isNullOrEmpty(articleAttachmentPOList)) {

            ArrayList<AttachmentVO> attachmentVOList = new ArrayList<>();
            articleAttachmentPOList.forEach(articleAttachmentPO -> {
                AttachmentVO attachmentVO = new AttachmentVO();
                attachmentVO.setAttachmentUrl(articleAttachmentPO.getAttachmentUrl());
                attachmentVO.setAttachmentName(articleAttachmentPO.getAttachmentUrl());
                attachmentVOList.add(attachmentVO);
            });
            String attachmentJson = JSON.toJSONString(attachmentVOList);
            // 进行添加
            articleAttachmentService.saveOrUpdateAttachment(copyArticleId, attachmentJson, userId);
        }
        // 获取相关文章信息
        QueryWrapper<ArticleRelevantPO> articleRelevantPOQueryWrapper = new QueryWrapper<>();
        articleRelevantPOQueryWrapper.eq("ARTICLE_ID", article.getId());
        List<ArticleRelevantPO> RelevantPOList = articleRelevantService.list(articleRelevantPOQueryWrapper);
        // 复制相关文章信息
        if (!ValidateUtil.isNullOrEmpty(RelevantPOList)) {
            ArrayList<ArticleRelevantVO> articleRelevantVOS = new ArrayList<>();
            for (ArticleRelevantPO articleRelevantPO : RelevantPOList) {
                ArticleRelevantVO relevantVO = new ArticleRelevantVO();
                relevantVO.setRelevantArticleId(articleRelevantPO.getRelevantArticleId());
                articleRelevantVOS.add(relevantVO);
            }
            String relevantJson = JSON.toJSONString(articleRelevantVOS);
            articleRelevantService.saveOrUpdateRelevent(copyArticleId, relevantJson, userId);

        }

        return true;
    }


    @ApiOperation(value = "引用栏目", notes = "引用栏目")
    @PostMapping("/reference-columns")
    public R referenceColumns(@ApiParam(value = "当前栏目id", required = true, example = "112345675646") @RequestParam(required = false) Long columnId,
                              @ApiParam(value = "被选中(引用)的栏目ids", required = true, example = "112345675646") @RequestParam(required = false) String selectedColumnIds,
                              @ApiParam(value = "引用后的文章状态(CAO_GAO(草稿)YI_FA_BU(已发布)YUAN_ZHUANG_TAI(原状态))", required = true, example = "CAO_GAO") @RequestParam(required = false) String referenceArticleStatus
            /*@RequestAttribute("userId") Long userId*/) {

        // 校验参数
        if (null == columnId || !ValidateUtil.Number(columnId) || columnId <= 0)
            return R.failureRequestParam().msg("栏目id为空或格式不正确");
        if (null == selectedColumnIds || StringUtils.isEmpty(selectedColumnIds))
            return R.failureRequestParam().msg("请选择你要引用的栏目id");
        if (StringUtils.isEmpty(referenceArticleStatus)) return R.failureRequestParam().msg("引用的文章状态不能为空");

        // 1、先将栏目字符串ids分割成一个数组->columnSplit
        String[] split = selectedColumnIds.split(",");
        // 因为id是Long类型的 创建一个数组存放
        ArrayList<Long> columnIdList = new ArrayList<>();
        // 对split进行遍历->split(String)转换成Long类型的 放到columnList中
        for (String columnSplit : split) {
            Long columnIdLong = Long.valueOf(columnSplit);
            columnIdList.add(columnIdLong);
        }

        // 如果当前栏目id有引用其他栏目,先删除关系 在重新新增关系
        QueryWrapper<ColumnReferenceRelationshipPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CURRENT_COLUMN_ID", columnId);
        boolean columnRemove = columnReferenceRelationshipService.remove(queryWrapper);
        // 去文章关系表中 也删除这个关系
        QueryWrapper<ColumnReferenceArticlePO> columnReferenceArticlePOQueryWrapper = new QueryWrapper<>();
        columnReferenceArticlePOQueryWrapper.eq("CURRENT_COLUMN_ID", columnId);
        boolean articleRemove = columnReferenceArticleService.remove(columnReferenceArticlePOQueryWrapper);


        for (Long id : columnIdList) {
            ColumnReferenceRelationshipPO relationshipPO = new ColumnReferenceRelationshipPO();
            relationshipPO.setCurrentColumnId(columnId);
            relationshipPO.setReferenceColumnId(id);
            relationshipPO.setArticleStatus(referenceArticleStatus);
            boolean saveResult = columnReferenceRelationshipService.save(relationshipPO);

            // 查被引用的栏目下的文章id
            QueryWrapper<ArticlePO> articlePOQueryWrapper = new QueryWrapper<>();
            articlePOQueryWrapper.eq("COLUMN_ID", id);
            List<ArticlePO> articlePOList = articleService.list(articlePOQueryWrapper);
            for (ArticlePO articlePO : articlePOList) {
                // 将引用的栏目下的文章，放进引用文章表中
                ColumnReferenceArticlePO columnReferenceArticlePO = new ColumnReferenceArticlePO();
                columnReferenceArticlePO.setCurrentColumnId(columnId);
                columnReferenceArticlePO.setReferenceColumnId(id);
                // 根据选择的状态设置文章状态     原状态 草稿 已发布
                if (ArticleEnum.STATUS_YI_FA_BU.getValue().equals(referenceArticleStatus)) {
                    columnReferenceArticlePO.setReferenceArticleStatus(referenceArticleStatus);
                } else if (ArticleEnum.STATUS_CAO_GAO.getValue().equals(referenceArticleStatus)) {
                    columnReferenceArticlePO.setReferenceArticleStatus(referenceArticleStatus);
                } else {
                    columnReferenceArticlePO.setReferenceArticleStatus(articlePO.getArticleStatus());
                }
                columnReferenceArticlePO.setReferenceArticleStatus(referenceArticleStatus);
                columnReferenceArticlePO.setReferenceArticleId(articlePO.getId());
                boolean articleSave = columnReferenceArticleService.save(columnReferenceArticlePO);
                if (!articleSave) return R.failure().msg("引用文章失败");
            }
            if (!saveResult) return R.failure().msg("引用栏目失败");
        }
        return R.success().msg("引用成功");
    }


    @ApiOperation(value = "获取引用栏目配置", notes = "获取引用栏目配置")
    @PostMapping("/get-reference-columns")
    public R<ReferenceColumnVO> getReferenceColumns(@ApiParam(value = "当前栏目id", required = true, example = "112345675646") @RequestParam(required = false) Long columnId,
                             @ApiParam(value = "站点id", required = true, example = "112345675646") @RequestParam(required = false) Long siteId,
                             @RequestAttribute("userId") Long userId) {
        // 参数校验
        if (null == columnId || !ValidateUtil.Number(columnId) || columnId <= 0) {
            return R.failureRequestParam().msg("栏目id为空或格式不正确");
        }
        if (null == siteId || !ValidateUtil.Number(siteId) || siteId <= 0) {
            return R.failureRequestParam().msg("站点id为空或格式不正确");
        }

        QueryWrapper<ColumnReferenceRelationshipPO> columnReferenceRelationshipPOQueryWrapper = new QueryWrapper<>();
        columnReferenceRelationshipPOQueryWrapper.lambda().eq(ColumnReferenceRelationshipPO::getCurrentColumnId, columnId);
        List<ColumnReferenceRelationshipPO> list = columnReferenceRelationshipService.list(columnReferenceRelationshipPOQueryWrapper);
        String referenceArticleStatus = "";
        ArrayList<String> selectedColumnIds = new ArrayList<>();
        if (null != list) {
            for (ColumnReferenceRelationshipPO columnReferenceRelationshipPO : list) {
                referenceArticleStatus = columnReferenceRelationshipPO.getArticleStatus();
                selectedColumnIds.add(String.valueOf(columnReferenceRelationshipPO.getReferenceColumnId()));
            }
        }

        ReferenceColumnVO referenceColumnVO = new ReferenceColumnVO();
        referenceColumnVO.setColumnId(columnId);
        referenceColumnVO.setReferenceArticleStatus(referenceArticleStatus);
        referenceColumnVO.setSelectedColumnIds(selectedColumnIds);

        return R.success().data(referenceColumnVO);
    }

}
